package cc.bookcloud.springboot3.auth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Configuration
public class UserDetailsConfig {

    // 密码编码器（BCrypt）
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 从数据库sys_user表加载用户
    @Bean
    public UserDetailsService userDetailsService(DataSource dataSource) {
        return username -> {
            // 查询用户（简化：直接用JDBC，实际可替换为JPA）
            try (Connection conn = dataSource.getConnection();
                 PreparedStatement ps = conn.prepareStatement("SELECT username, password, enabled FROM sys_user WHERE username = ?")) {
                ps.setString(1, username);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    return User.withUsername(rs.getString("username"))
                            .password(rs.getString("password")) // 数据库中已BCrypt加密的密码
                            .disabled(!rs.getBoolean("enabled"))
                            .authorities("ROLE_USER") // 简化：固定角色，实际应从sys_role查询
                            .build();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            throw new UsernameNotFoundException("用户不存在：" + username);
        };
    }
}